

/*
 * @Author: likang xie 
 * @Date: 2018-06-15 11:39:55 
 * @Purpose: 登录
 */

(function () {

  // 全局变量
  var $ = null;
  var form = null;
  var loging = false;

  // 使用模块
  layui.use(['jquery', 'form'], function () {
    $ = layui.$;
    form = layui.form;
    btgo.getRsa($);
    bindEvent(); // 绑定事件
  });

  // 绑定事件
  function bindEvent() {
    // 登录提交
    form.on('submit(login)', function (data) {
      var formdata = data.field;
      var elem = data.elem;
      !loging && login(formdata, elem);
    });

    // 验证码刷新
    $('.code img').on('click', refleshCode);

    // 回车键
    btgo.enter($, {
      el: '.form-container',
      callback: function callback() {
        $('.login-btn').click();
      }
    });
  }

  // 登录
  function login(form, elem) {
    elem.innerText = '登录中...';
    loging = true;
    var url = '?r=userlogin/login';
    // 获取登录时间
    btgo.request($, {
      url: url,
      data: {
        action: 'time'
      },
      success: function success(res) {
        // 登录
        if (res.status == 200) {
          var data = btgo.encrypt({
            username: form.username,
            password: form.password,
            time: res.data.time
          });
          btgo.request($, {
            url: url,
            type: 'post',
            data: {
              loginencrypt: data,
              vaildcode: form.code
            },
            success: function success(res) {
              console.log(res);
              if (res.status == 200) {
                window.location.href = res.data.url;
              }
              if (res.vaildcodeshow == 1) {
                $('.code-row').addClass('layui-show');
              }
              loging = false;
              elem.innerText = '登录';
              btgo.msg(res.message);
            },
            error: function error(res) {
              console.log(res);
              btgo.msg('服务器异常，请重试');
              elem.innerText = '登录';
              loging = false;
            }
          });
        }
      }
    });
  }

  // 验证码刷新
  function refleshCode() {
    var timestamp = new Date().valueOf();
    this.src = '?r=userlogin/verify&timestamp=' + timestamp;
  }
})();